﻿using System;
using System.Linq;
using System.Net;
using System.Web;

namespace WebDotNet.Extensions
{
	public static class HttpContextBaseExtensions
	{
		private const string HttpContextBaseParameter = "httpContextBase";
		public const string AjaxHeaderKey = "X-Requested-With";
		public const string AjaxHeaderValue = "XMLHttpRequest";

		public static bool IsAjaxRequest(this HttpContextBase httpContextBase)
		{
			if (httpContextBase == null) throw new ArgumentNullException(HttpContextBaseParameter);

			return httpContextBase.Request.Headers[AjaxHeaderKey] != null && httpContextBase.Request.Headers[AjaxHeaderKey] == AjaxHeaderValue;
		}

		public static void SetResponseHeader(this HttpContextBase httpContextBase, string name, string value, bool replace)
		{
			if (httpContextBase == null) throw new ArgumentNullException(HttpContextBaseParameter);

			if (replace)
			{
				httpContextBase.Response.AddHeader(name, value);
			}
			else
			{

				if (!httpContextBase.Response.Headers.AllKeys.Any(k => k == name))
				{
					httpContextBase.Response.AddHeader(name, value);
				}
			}
		}

		public static void Redirect(this HttpContextBase httpContextBase, string url)
		{
			if (httpContextBase == null) throw new ArgumentNullException(HttpContextBaseParameter);

			httpContextBase.Response.StatusCode = (int)HttpStatusCode.Redirect;
			httpContextBase.SetResponseHeader(HttpResponseHeader.Location.ToString(), url, true);
		}

		public static void SeeOther(this HttpContextBase httpContextBase, string url)
		{
			if (httpContextBase == null) throw new ArgumentNullException(HttpContextBaseParameter);

			httpContextBase.Response.StatusCode = (int)HttpStatusCode.SeeOther;
			httpContextBase.SetResponseHeader(HttpResponseHeader.Location.ToString(), url, true);
		}

		public static void NotFound(this HttpContextBase httpContextBase)
		{
			if (httpContextBase == null) throw new ArgumentNullException(HttpContextBaseParameter);

			httpContextBase.Response.StatusCode = (int)HttpStatusCode.NotFound;
		}
	}
}
